package com.dhj.service.impl;

import com.dhj.baseBean.ResponseResult;
import com.dhj.entity.LoginUser;
import com.dhj.entity.User;
import com.dhj.service.LoginService;
import com.dhj.utils.JwtUtil;
import com.dhj.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author DaHuaJia
 * @Description 用户登录登出service实现层
 * @Date 2022-03-20 15:12:35
 */
@Service
public class LoginServiceImpl implements LoginService {


    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;


    @Override
    public ResponseResult login(User user) {

        /**
         * AuthenticationManager authenticate进行用户认证
         */
        // 通过UsernamePasswordAuthenticationToken将用户名和密码封装
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        // 通过authenticationManager帮助我们进行校验
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        // 如果认证没通过，给出对应的提示
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("登录失败！");
        }

        // 如果认证通过了，则使用userId生成jwt，jwt存入responseResult 返回
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        // 获取jwt
        String jwt = JwtUtil.createJWT(userId);

        // 把完整的用户信息存入redis，userId作为key
        redisCache.setCacheObject("login:" + userId, loginUser);

        // 返回数据
        Map data = new HashMap();
        data.put("token", jwt);
        return new ResponseResult(200, "登录成功", data);
    }


    /**
     * 退出登录
     *
     * @return
     */
    @Override
    public ResponseResult logout() {
        // 获取SecurityContextHolder 中的用户id
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String userId = loginUser.getUser().getId().toString();

        // 删除redis中的值
        redisCache.deleteObject("login:" + userId);

        return new ResponseResult(200, "注销成功");
    }

}
